/**
 * <p>文件名: FileUtil.java</p>
 * <p>版权声明: Copyright &copy; 2008-2009 中科软科技股份有限公司</p>
 * <p>创建者: 王明龙</p>
 * <p>创建时间: 2009-6-16  下午04:34:13</p>
 */
package com.tjtt.tdm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 操作文件
 */
public class FileUtil {

	/**
	 * 文件另存为
	 * @param fromFile
	 * @param toFile
	 * @return boolean
	 * @author 王明龙
	 * @throws IOException 
	 */
	public static boolean saveAs(File fromFile, File toFile) throws IOException {
		InputStream in = null;
		OutputStream os = null;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		boolean success = false;
		try {
			fis = new FileInputStream(fromFile);
			in = fis;
			fos = new FileOutputStream(toFile);
			int len = 0;
			os = fos;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}
			os.flush();
			success = true;
		}
		catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
		finally {
			try {
				if (fos != null) {
					fos.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (fis != null) {
					fis.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (os != null) {
					os.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (in != null) {
					in.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return success;
	}
	/**
     * 
     * 读取某个文件夹下的所有文件夹和文件, 返回所有文件名
     * @param filepath String 
     * @throws FileNotFoundException 
     * @throws IOException 
     * @return Map<Integer, String> pathMap
     * 
     */ 
	public static Map<Integer, String> readfile(String filepath,
			Map<Integer, String> pathMap) throws Exception {
		if (pathMap == null) {
			pathMap = new HashMap<Integer, String>();
		}
		File file = new File(filepath);
		if(file.exists()){
			// 文件
			if (!file.isDirectory()) {
				pathMap.put(pathMap.size(), file.getPath());

			} else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "/" + filelist[i]);
					if (!readfile.isDirectory()) {
						pathMap.put(pathMap.size(), readfile.getPath());

					} else if (readfile.isDirectory()) { // 子目录的目录
						readfile(filepath + "/" + filelist[i], pathMap);
					}
				}
			}
		}
		return pathMap;
	}
	 /**
     * 获取文件存放路径
     * @param url    根目录
     * @param projectNo	项目编号
     * @return String
     * @author 娄肖建
     * @date Jun 11, 2014 10:29:07 AM
     */
    public static String getFileUrl(String url,String projectNo){
    	File file1 = new File(DateFormatUtil.getYear()+"");
		if ( ! (file1.exists())  &&   ! (file1.isDirectory()))  {
             boolean  creadok  =  file1.mkdirs();
             if (creadok)  {
                System.out.println( " ok:创建文件夹成功！ " );
            } else  {
                System.out.println( " err:创建文件夹失败！ " );                    
            } 
        } 
		File file2 = new File(DateFormatUtil.getMonth()+"");
		if ( ! (file2.exists())  &&   ! (file2.isDirectory()))  {
             boolean  creadok  =  file2.mkdirs();
             if (creadok)  {
                System.out.println( " ok:创建文件夹成功！ " );
            } else  {
                System.out.println( " err:创建文件夹失败！ " );                    
            } 
        }
		File file3 = new File(projectNo);
		if ( ! (file3.exists())  &&   ! (file3.isDirectory()))  {
             boolean  creadok  =  file3.mkdirs();
             if (creadok)  {
                System.out.println( " ok:创建文件夹成功！ " );
            } else  {
                System.out.println( " err:创建文件夹失败！ " );                    
            } 
        }//40720146ewww
		int month=DateFormatUtil.getMonth();
		String reslut=url+"/"+DateFormatUtil.getYear()+"/"+(month<10?("0"+month):month)+"/"+projectNo;
		return reslut;
	}
	/**
	 * 文件另存为
	 * @param fromFile
	 * @param toFilePath
	 * @return boolean
	 * @author 王明龙
	 * @throws IOException 
	 */
	public static boolean saveAs(File fromFile, String toFilePath) throws IOException {
		File toFile = new File(toFilePath);
		return saveAs(fromFile, toFile);
	}
	
	
	/**
	 * 文件另存为
	 * @param fromFile
	 * @param toFileURI
	 * @return boolean
	 * @author 王明龙
	 * @throws IOException 
	 */
	public static boolean saveAs(File fromFile, URL toFileURL) throws IOException {
		File toFile = new File(toFileURL.getPath());
		return saveAs(fromFile, toFile);
	}
	
	
	/**
	 * 截取文件的后缀名
	 * @param fileName
	 * @return String
	 * @author 王明龙
	 */
	public static String subPostfix(String fileName){
		return fileName.substring(fileName.lastIndexOf("."),fileName.length());
	}
	public void zip(String inputFileName, String zipFileName) throws Exception {  
        zip(zipFileName, new File(inputFileName));  
    }  
  
    private void zip(String zipFileName, File inputFile) throws Exception {  
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));  
        zip(out, inputFile, "");  
        out.close();  
    }  
  
    private void zip(ZipOutputStream out, File f, String base) throws Exception {  
        if (f.isDirectory()) {  //�ж��Ƿ�ΪĿ¼  
            File[] fl = f.listFiles();  
            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));  
            base = base.length() == 0 ? "" : base + "/";  
            for (int i = 0; i < fl.length; i++) {  
                zip(out, fl[i], base + fl[i].getName());  
            }  
        } else {                //ѹ��Ŀ¼�е������ļ�  
            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));  
            FileInputStream in = new FileInputStream(f);  
            int b;  
            while ((b = in.read()) != -1) {  
                out.write(b);  
            }  
            in.close();  
        }  
    }  
    /**
     * 解压缩zip文件
     * @param zipFilePath
     * @param saveFilePath
     * @throws IOException 
     * void
     * @author 夏明涛
     * @date Nov 22, 2010 9:16:41 AM
     */
    public static void unzip(String zipFilePath,String saveFilePath) throws IOException,FileNotFoundException {
		if("".equals(saveFilePath)){
			saveFilePath = zipFilePath.substring(0,zipFilePath.lastIndexOf(File.separator));
		}
		ZipFile zipFile = new ZipFile(zipFilePath);
    	Enumeration<ZipEntry> zipEnties = zipFile.getEntries();
    	while(zipEnties.hasMoreElements()){
    		processSingleEntry(zipFile,zipEnties.nextElement(),saveFilePath);
    	}
    	zipFile.close();
	}
    private static void processSingleEntry(ZipFile zipFile,ZipEntry zipEntry,String saveFilePath) throws IOException,FileNotFoundException{
    	byte[] temp = new byte[1024];
    	if(zipEntry.isDirectory()){
    		File file = new File(saveFilePath+File.separator+zipEntry.getName());
    		if(!file.exists()){
    			file.mkdirs();
    		}
    	}else{
    		File file = new File(saveFilePath+File.separator+zipEntry.getName());
    		if(file.exists()){
    			file.delete();
    		}
    			FileOutputStream out = new FileOutputStream(file);
    			InputStream input = zipFile.getInputStream(zipEntry);
    			int length = input.read(temp);
    			while(length!=-1){
    				out.write(temp, 0, length);
    				length = input.read(temp);
    			}
    			out.flush();
    			out.close();
    			input.close();
    	}
    }
    
}
